using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Users;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Users
{
    public class ResetPwdCommandHandler : IRequestHandler<ResetPwdCommand, APIResult<int>>
    {
        private readonly IBaseRepository<User> _userRep;
        private readonly IVerificationCodeService _verificationCodeService;
        private readonly ILogger<ResetPwdCommandHandler> _logger;

        public ResetPwdCommandHandler(
            IBaseRepository<User> userRep,
            IVerificationCodeService verificationCodeService,
            ILogger<ResetPwdCommandHandler> logger)
        {
            _userRep = userRep ?? throw new ArgumentNullException(nameof(userRep));
            _verificationCodeService = verificationCodeService ?? throw new ArgumentNullException(nameof(verificationCodeService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task<APIResult<int>> Handle(ResetPwdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (string.IsNullOrEmpty(request.UserPhone) || string.IsNullOrEmpty(request.Code) || string.IsNullOrEmpty(request.NewPwd))
                {
                    _logger.LogWarning("重置密码参数不完整");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "参数不完整",
                        Data = 0
                    };
                }

                // 查找用户
                var user = await _userRep.GetAll()
                    .FirstOrDefaultAsync(u => u.UserPhone == request.UserPhone && !u.IsDel);

                if (user == null)
                {
                    _logger.LogWarning($"未找到手机号为 {request.UserPhone} 的用户");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "用户不存在",
                        Data = 0
                    };
                }

                // 验证验证码
                bool isValidCode = await _verificationCodeService.ValidateCodeAsync(request.UserPhone, request.Code);
                if (!isValidCode)
                {
                    _logger.LogWarning($"验证码错误或已过期: {request.UserPhone}");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "验证码错误或已过期",
                        Data = 0
                    };
                }

                // 更新密码
                user.UserPwd = request.NewPwd.GetMD5();
                user.UpdateTime = DateTime.Now;
                await _userRep.UpdAsync(user);

                // 移除已使用的验证码
                await _verificationCodeService.RemoveCodeAsync(request.UserPhone);

                _logger.LogInformation($"用户 {user.UserName} 密码重置成功");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "密码重置成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"重置密码时发生错误: {request.UserPhone}");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "密码重置失败",
                    Data = 0
                };
            }
        }
    }
} 